import json
import tkinter as tk
from tkinter import ttk

# 加载训读词库
def load_hanzi_mapping(HANZI_MAPPING):
    with open(HANZI_MAPPING, 'r', encoding='utf-8') as f:
        return json.load(f)

# 修改初始化部分
class HanziInputMethod:
    def __init__(self, root):
        self.HANZI_MAPPING = load_hanzi_mapping("HANZI_MAPPING.json")  # 替换原有HANZI_MAPPING
        self.root = root
        root.title("英语训读输入法")
        
        # 输入框
        self.input_text = tk.Text(root, height=5, font=("Arial", 14))
        self.input_text.pack(pady=10)
        self.input_text.bind("<KeyRelease>", self.check_replace)
        
        # 候选框
        self.candidate_list = tk.Listbox(root, font=("楷体", 14), 
                                      height=4, selectbackground="#c0c0c0")
        self.candidate_list.bind("<<ListboxSelect>>", self.do_replace)
        self.candidate_list.place_forget()  # 初始隐藏
        
        # 状态栏
        self.status = ttk.Label(root, text="输入英文单词自动提示训读汉字")
        self.status.pack(side=tk.BOTTOM, fill=tk.X)

    def check_replace(self, event):
        # 获取当前输入内容
        text = self.input_text.get("1.0", "end-1c").strip()  # 增加strip处理
        
        # 修复1：处理空输入的情况
        if not text:
            self.candidate_list.place_forget()
            return
        
        # 修复2：安全获取最后一个单词
        words = text.split()
        if not words:  # 处理只有空格的情况
            self.candidate_list.place_forget()
            return
            
        last_word = words[-1].lower()  # 安全访问
        
        # 匹配候选词（原有逻辑保持不变）
        candidates = []
        for length in range(len(last_word), 0, -1):
            substr = last_word[:length]
            if substr in self.HANZI_MAPPING:
                candidates.append((
                    substr, 
                    self.HANZI_MAPPING[substr],
                    f"{substr} → {self.HANZI_MAPPING[substr]}"
                ))
        
        # 显示候选框
        if candidates:
            self.show_candidates(candidates, event)
        else:
            self.candidate_list.place_forget()

    def show_candidates(self, candidates, event):
        # 清空候选列表
        self.candidate_list.delete(0, tk.END)
        
        # 添加候选项
        for _, hanzi, display in candidates[:4]:  # 最多显示4个
            self.candidate_list.insert(tk.END, display)
        
        # 定位候选框
        x, y = self.input_text.bbox(tk.INSERT)[:2]
        self.candidate_list.place(
            x=x + 30, 
            y=y + 50, 
            relx=0, 
            rely=0
        )

    def do_replace(self, event):
        # 获取选中项
        selection = self.candidate_list.curselection()
        if not selection:
            return
        
        # 获取替换内容
        selected = self.candidate_list.get(selection[0])
        original, hanzi = selected.split(" → ")
        
        # 替换最后一个单词
        text = self.input_text.get("1.0", "end-1c").split()
        text[-1] = hanzi
        self.input_text.delete("1.0", tk.END)
        self.input_text.insert(tk.END, " ".join(text))
        
        self.candidate_list.place_forget()

if __name__ == "__main__":
    root = tk.Tk()
    app = HanziInputMethod(root)
    root.geometry("800x400")
    root.mainloop()
    #整理到一百个了